package com.upcode.weighing.oauthserver.config;

import com.upcode.weighing.oauthserver.dto.UserInfoDTO;
import com.upcode.weighing.util.SensitiveInfoUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;

import java.util.HashMap;
import java.util.Map;

/**
 * token生成携带的信息
 * @author Administrator
 * @date 2018/2/2
 * modified by LeiDong 2021/06/01 for return idCardNo and openId back
 */
public class CustomTokenEnhancer implements TokenEnhancer {
    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        Authentication userAuthentication = authentication.getUserAuthentication();
        if(userAuthentication != null) {
            final Map<String, Object> additionalInfo = new HashMap<>();
            UserInfoDTO user = (UserInfoDTO) userAuthentication.getPrincipal();
            additionalInfo.put("id",user.getId());
            additionalInfo.put("name", user.getName());
            additionalInfo.put("username", user.getUsername());
            additionalInfo.put("photoAddr", user.getPhotoAddr());
            additionalInfo.put("idcardNo", user.getIdcardNo());
            additionalInfo.put("telephone", user.getTelephone());
            /*String idCardNo = user.getIdcardNo();
            if (idCardNo != null){
                //身份证号回显脱敏
                additionalInfo.put("idcardNo", SensitiveInfoUtils.sensitiveIdCard(idCardNo));
            }*/
            /*String telephone = user.getTelephone();
            if (telephone != null){
                //手机号回显脱敏
                additionalInfo.put("telephone", SensitiveInfoUtils.sensitiveTel(telephone));
            }*/
//          additionalInfo.put("authorities", user.getAuthorities());
            ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
        }
        return accessToken;
    }
}
